package cn.csc.module.order.controller.app.shopcart;

import cn.csc.framework.common.pojo.CommonResult;
import cn.csc.module.member.api.user.MemberUserApi;
import cn.csc.module.member.api.user.dto.MemberUserRespDTO;
import cn.csc.module.order.controller.app.shopcart.vo.*;
import cn.csc.module.order.convert.shopcart.ShopCartItemConvert;
import cn.csc.module.order.dal.dataobject.shopcart.ShopCartItemDO;
import cn.csc.module.order.enums.ErrorCodeConstants;
import cn.csc.module.order.service.shopcart.ShopCartItemService;
import cn.csc.module.product.api.sku.SkuApi;
import cn.csc.module.product.api.sku.dto.SkuDTO;
import cn.csc.module.product.api.spu.SpuApi;
import cn.csc.module.product.api.spu.dto.SpuDTO;
import cn.csc.module.shop.api.detail.ShopDetailApi;
import cn.csc.module.shop.api.detail.dto.ShopDetailRespDTO;
import cn.hutool.json.JSONArray;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static cn.csc.framework.common.pojo.CommonResult.success;
import static cn.csc.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Api(tags = "用户 APP - 购物车")
@RestController
@RequestMapping("/order/shopCart")
@Validated
@Slf4j
public class AppShopCartItemController {

    @Resource
    private ShopCartItemService shopCartItemService;
    @Autowired
    private ShopDetailApi shopDetailApi;
    @Autowired
    private SkuApi skuApi;
    @Autowired
    private SpuApi spuApi;
    @Resource
    private MemberUserApi memberUserApi;

    @GetMapping("/list")
    @ApiOperation("获得购物车列表")
    @PermitAll
    public CommonResult<List<AppShopCartRespVO>> getShopCartItemList() {
        Long userId=getLoginUserId();
        log.info("[getShopCartItemList][userId]:{}",userId);
        if(userId == null){
            return success();
        }
        List<ShopCartItemDO> list= shopCartItemService.getShopCartItemList(BigInteger.valueOf(userId));
        log.info("[AppShopCartItemController][getShopCartItemList]userId:{},BigInteger:{}",userId);
        if(list.isEmpty()){
            //购物车没有商品
            return success();
        }
        //是否是供应商，供应商取供应商价格
        MemberUserRespDTO memberUserRespDTO=memberUserApi.getUser(getLoginUserId()).getData();
        log.info("[AppShopCartItemController][getShopCartItemList]userId:{},memberUserRespDTO:{}",memberUserRespDTO);
        int userType = memberUserRespDTO != null ? memberUserRespDTO.getType() : 0;
        List<BigInteger> shopIds=list.stream().map(c ->c.getShopId()).collect(Collectors.toList());
        List<ShopCartItemDO> cartItemLists=shopCartItemService.selectShopIdsList(BigInteger.valueOf(userId),shopIds);
        List<ShopDetailRespDTO> shopDetailRespDTOS=shopDetailApi.getShopDetailList(shopIds).getCheckedData();
        List<SpuDTO> spuDtos=spuApi.getSpuList(cartItemLists.stream().map(c ->c.getSpuId()).collect(Collectors.toList())).getCheckedData();
        List<SkuDTO> skuDtos=skuApi.getSkuList(cartItemLists.stream().map(c ->c.getSkuId()).collect(Collectors.toList())).getCheckedData();

        List<AppShopCartRespVO> resultLis=new ArrayList<>();
        for(ShopCartItemDO cartDO:list){
            AppShopCartRespVO cartRespVO= new AppShopCartRespVO();
            cartRespVO.setShopId(cartDO.getShopId());
            cartRespVO.setShopName(shopDetailRespDTOS.stream().filter(e -> e.getId().equals(cartDO.getShopId())).findFirst().orElse(null).getShopName() );
            List<ShopCartItemDO> cartItems=cartItemLists.stream().filter(c ->c.getShopId().equals(cartDO.getShopId())).collect(Collectors.toList());
            List<AppShopCartListRespVO> shopCartItems= new ArrayList<>();

            for(ShopCartItemDO cartItemDO:cartItems){
                AppShopCartListRespVO listVO=ShopCartItemConvert.INSTANCE.convert02(cartItemDO);
                SpuDTO spuDTO=spuDtos.stream().filter(e -> e.getId().equals(cartItemDO.getSpuId())).findFirst().orElse(null);// spuApi.getSpu(BigInteger.valueOf()).getData();
                if(spuDTO!=null && spuDTO.getVerifyStatus()==10){
                    SkuDTO skuDTO = skuDtos.stream().filter(e -> e.getId().equals(cartItemDO.getSkuId())).findFirst().orElse(null);
                    listVO.setSkuName(skuDTO.getSkuName())
                          .setImgUrl(skuDTO.getImgUrl())
                          .setSpuName(spuDTO.getName())
                          .setPriceFee(userType==5 || userType==15 ? skuDTO.getShopPriceFee():skuDTO.getPriceFee());
                    shopCartItems.add(listVO);
                }
            }
            if(!shopCartItems.isEmpty()){
                cartRespVO.setShopCartItems(shopCartItems);
                resultLis.add(cartRespVO);
            }
        }
        return success(resultLis);
    }

    /**
     * 加入购物车
     *
     * @return
     */
    @PostMapping("/add")
    @Operation(summary = "加入购物车", description = "加入购物车")
    public CommonResult<BigInteger> addCart(@Valid @RequestBody AppShopCartItemUpdateReqVO reqVO) {
        //查询skuId是否已存在，存在数量加1，否则新增
        reqVO.setUserId(getLoginUserId());
        ShopCartItemDO item=shopCartItemService.getShopCartItem(reqVO);
        log.info("[AppShopCartItemController][addCart]item:{},",item);
        if(item!=null && !Objects.isNull(item.getId())){//存在数量加1
            log.info("[AppShopCartItemController][addCart]updateShopCartItem:{},",item);
            reqVO.setCount(item.getCount()+reqVO.getCount());
            reqVO.setId(item.getId());
            shopCartItemService.updateShopCartItem(reqVO);
        }else{//否则新增
            AppShopCartItemCreateReqVO createReqVO=ShopCartItemConvert.INSTANCE.convert01(reqVO);
            shopCartItemService.createShopCartItem(createReqVO);
        }
        return success();
    }
    /**
     * delete购物车
     *
     * @return
     */
    @PostMapping("/delete")
    @Operation(summary = "删除购物车", description = "删除购物车")
    public CommonResult<BigInteger> delete(@Valid @RequestBody AppShopCartItemDeleteReqVO reqVO) {
        shopCartItemService.deleteShopCartItem(reqVO.getId());
        return success();
    }
    /**
     * 编辑购物车
     *
     * @return
     */
    @PostMapping("/update")
    @Operation(summary = "编辑购物车", description = "编辑购物车")
    public CommonResult<BigInteger> update(@Valid @RequestBody AppShopCartItemDeleteReqVO reqVO) {
        shopCartItemService.updateShopCartItem(ShopCartItemConvert.INSTANCE.convert(reqVO));
        return success();
    }
}
